package util.core;

import org.apache.commons.lang3.StringEscapeUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by WhiteBlue on 15/5/10.
 */
public abstract class FormValidator {

    private HttpServletRequest request;
    private boolean flag = true;

    public FormValidator(HttpServletRequest request) {
        this.request = request;
        this.validate();
    }

    public abstract void validate();

    public boolean verify() {
        return this.flag;
    }


    public String getString(String name) {
        return StringEscapeUtils.escapeHtml4(request.getParameter(name));
    }

    public int getInt(String name, int defaultValue) {
        try {
            String value = request.getParameter(name);
            return Integer.parseInt(value);
        } catch (Exception e) {
            e.printStackTrace();
            return defaultValue;
        }
    }

    public void validateString(String name, boolean notBlank, int minLen, int maxLen) {
        try {
            String value = request.getParameter(name);
            if (value == null) {
                if (notBlank)
                    flag = false;
            } else {
                if (!("".equals(value.trim()))) {
                    if (value.length() <= minLen && value.length() >= maxLen)
                        flag = false;
                } else {
                    if (notBlank)
                        flag = false;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
    }


    public void validateNumber(String name, boolean notBlank, int minLen, int maxLen) {
        try {
            String value = request.getParameter(name);
            if (value == null) {
                if (notBlank)
                    flag = false;
            } else {
                if (!("".equals(value.trim()))) {
                    if (value.length() >= minLen && value.length() <= maxLen) {
                        if (!value.matches("\\d+"))
                            flag = false;
                    } else
                        flag = false;
                } else {
                    if (notBlank)
                        flag = false;
                }
            }

        } catch (
                Exception e
                )

        {
            flag = false;
        }

    }


    public void validateInt(String name, boolean notBlank, int min, int max) {
        try {
            String value = request.getParameter(name);
            int temp = Integer.parseInt(value);
            if (temp < min || temp > max) {
                flag = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
    }
}
